package com.huike.business.domain.service.impl;

import com.huike.business.domain.TbBusiness;
import com.huike.business.domain.TbBusinessTrackRecord;
import com.huike.business.domain.mapper.TbBusinessMapper;
import com.huike.business.domain.service.TbBusinessService;
import com.huike.business.domain.vo.BusinessTrackVo;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.TbRulePool;
import com.huike.clues.domain.vo.AssignmentVo;
import com.huike.clues.mapper.SysUserMapper;
import com.huike.clues.mapper.TbAssignRecordMapper;
import com.huike.clues.service.TbRulePoolService;
import com.huike.clues.utils.JobUtils;
import com.huike.common.core.domain.entity.SysUser;
import com.huike.common.exception.CustomException;
import com.huike.common.utils.DateUtils;
import com.huike.common.utils.SecurityUtils;
import com.huike.common.utils.bean.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Service
public class TbBusinessServiceImpl implements TbBusinessService {

    @Resource
    private TbBusinessMapper tbBusinessMapper;
    @Resource
    private TbRulePoolService tbRulePoolService;
    @Resource
    private TbAssignRecordMapper tbAssignRecordMapper;
    @Resource
    private SysUserMapper sysUserMapper;


    @Override
    public void followAdded(BusinessTrackVo businessTrackVo) {
        tbBusinessMapper.followInsert(businessTrackVo);
    }

    /**
     * 查询商机跟进记录列表
     *
     * @param id
     * @return
     */
    @Override
    public List followSelect(Long id) {
        return tbBusinessMapper.followSelect(id);
    }

    /**
     * 获取商机跟进记录详细信息
     *
     * @param businessTrackVo
     * @return
     */
    @Override
    public TbBusinessTrackRecord detailed(BusinessTrackVo businessTrackVo) {
        TbBusinessTrackRecord tbBusinessTrackRecord = tbBusinessMapper.detailed(businessTrackVo);
        BeanUtils.copyProperties(businessTrackVo,tbBusinessTrackRecord);
        return tbBusinessTrackRecord;
    }
    @Override
    public List<TbBusiness> selectUserList(TbBusiness user) {
        return tbBusinessMapper.selectUserList(user);
    }

    @Override
    public List<TbBusiness> selectListPool(TbBusiness user) {
        return tbBusinessMapper.selectListPool(user);
    }

    @Override
    public void deletedList(List<Long> ids) {
        tbBusinessMapper.deletedList(ids);
    }

    @Override
    public TbBusiness findDetalisById(Long id) {
        TbBusiness tbBusiness = tbBusinessMapper.findDetalisById(id);
        return tbBusiness;
    }

    @Override
    public String addTbBusiness(TbBusiness tbBusiness) {
        LocalDateTime localDateTime = LocalDateTime.now();
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        tbBusiness.setCreateTime(date);
        tbBusiness.setUpdateTime(date);
        tbBusinessMapper.add(tbBusiness);

        return null;
    }

    /**
     * 修改商机
     *
     * @param tbBusiness
     * @return
     */
    @Override
    public String updateTbBusiness(TbBusiness tbBusiness) {
        LocalDateTime localDateTime = LocalDateTime.now();
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        tbBusiness.setCreateTime(date);
        tbBusinessMapper.update(tbBusiness);
        return null;
    }

    /**
     * 踢回公海
     *
     * @param id
     * @param reason
     * @return
     */
    @Override
    public String businessBack(Integer id, String reason) {
        Long businessId = Long.valueOf(id.longValue());
        TbBusiness tbBusiness = tbBusinessMapper.findById(businessId);
        LocalDateTime localDateTime = LocalDateTime.now();
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        tbBusiness.setUpdateTime(date);
        tbBusiness.setReasons(reason);
        tbBusiness.setStatus("4");
        tbBusinessMapper.update(tbBusiness);

        return reason;
    }

    /**
     * 捞取
     *@param businessIds
     * @param userId
     */
    @Override
    public String gain(Long[] businessIds, Long userId) {
        boolean isBatch= businessIds.length > 1? true: false;
        TbRulePool rulePool= tbRulePoolService.selectTbRulePoolByType(TbRulePool.RuleType.BUSINESS.getValue());
        // 统计当前分配人所有线索
        int assignRecords = tbAssignRecordMapper.countAssignBusinessByUser(userId);
        if(assignRecords>=rulePool.getMaxNunmber()){
            throw new CustomException("捞取失败！最大保有量("+rulePool.getMaxNunmber()+")，剩余可以捞取"+(rulePool.getMaxNunmber()-assignRecords)+"条商机");
        }
        for (int i = 0; i < businessIds.length; i++) {
            Long businessId = businessIds[i];

            //超过最大保有量
            if(assignRecords+i>=rulePool.getMaxNunmber()){
                throw  new CustomException("超过最大保有量，部分捞取成功，成功数目"+(i+1)+"条");
            }
            //重复捞取时间限制
            TbAssignRecord businessAssignRecord= tbAssignRecordMapper.selectAssignRecordByAssignId(businessId, TbAssignRecord.RecordType.BUSNIESS.getValue());
            if(businessAssignRecord!=null&&businessAssignRecord.getUserId().equals(userId)){
                Date repeatGetTime = JobUtils.getDate(rulePool.getRepeatGetTime().intValue(),
                        rulePool.getRepeatType(), businessAssignRecord.getCreateTime());
                //捞取限制时间内，不让捞取
                if(DateUtils.getNowDate().before(repeatGetTime)){
                    //批量捞取跳过
                    if(isBatch){
                        continue;
                    }else{
                        throw new CustomException("捞取失败！需要在 "+ DateUtils.dateTime(repeatGetTime)+" 后捞取");
                    }
                }
            }
            updateStatus(businessId, TbClue.StatusType.UNFOLLOWED.getValue());

            TbAssignRecord tbAssignRecord = addNewRecord(businessId,userId);
            //修改结束时间
            LocalDateTime localDateTime = LocalDateTime.now();
            Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            tbBusinessMapper.updateBusinessEndTimeById(businessId,date);
        }
        return "全部捞取成功";

    }

    public TbAssignRecord addNewRecord(Long id,Long userId){
        //保留上一条分配记录
        tbAssignRecordMapper.updateLatest(id,TbAssignRecord.RecordType.BUSNIESS.getValue());
        //新建分配记录
        TbAssignRecord tbAssignRecord =new TbAssignRecord();
        tbAssignRecord.setAssignId(id);
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        tbAssignRecord.setUserId(userId);
        tbAssignRecord.setDeptId(sysUser.getDeptId());
        tbAssignRecord.setUserName(sysUser.getUserName());
        Date now=DateUtils.getNowDate();
        tbAssignRecord.setCreateTime(now);
        tbAssignRecord.setCreateBy(SecurityUtils.getUsername());
        tbAssignRecord.setType(TbAssignRecord.RecordType.BUSNIESS.getValue());
        tbAssignRecordMapper.add(tbAssignRecord);
        return tbAssignRecord;
    }


    @Override
    public String assign(Long[] clueIds, Long userId) {
        return null;
    }

    @Override
    public int changeBusiness(Long clueId) {
        return 0;
    }

    @Override
    public int updateStatus(Long id, String status) {
        return 0;
    }

    /**
     * 商机分配
     * @param assignmentVo
     */
    @Override
    public String assignmentTbBusiness(AssignmentVo assignmentVo) {
        TbRulePool rulePool= tbRulePoolService.selectTbRulePoolByType(TbRulePool.RuleType.BUSINESS.getValue());
        //统计当前分配人所有线索
        int assignRecords= tbAssignRecordMapper.countAssignBusinessByUser(assignmentVo.getUserId());
        if(assignRecords>=rulePool.getMaxNunmber()){
            return "分配失败！保有量达到上线，最多选择"+rulePool.getMaxNunmber()+"条线索";
        }
        Long[] businessIds = assignmentVo.getIds();
        for (int i = 0; i < businessIds.length; i++) {
            Long businessId = businessIds[i];

            //超过最大保有量
            if(assignRecords+i>=rulePool.getMaxNunmber()){
                return "超过当前用户最大保有量，部分分配成功";
            }
            updateStatus(businessId, TbClue.StatusType.UNFOLLOWED.getValue());
            //从新分配
            TbAssignRecord record= addNewRecord(businessId,assignmentVo.getUserId());
            //修改结束时间
            LocalDateTime localDateTime = LocalDateTime.now();
            Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            tbBusinessMapper.updateBusinessEndTimeById(businessId,date);
        }
        return "全部分配";

    }



}
